package com.tianbing.adlottery.controller.user;

import org.apache.log4j.Logger;
import org.apache.oro.text.perl.Perl5Util;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.fengniu.ejb.dao.IUserDao;
import com.fengniu.ejb.entity.User;
import com.tianbing.adlottery.util.ControllerFormBean;

public class LoginValidator implements Validator {
	private static final String EMAIL_REGEXP = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";

	static Logger logger = Logger.getLogger(LoginValidator.class.getName());

	private IUserDao userDao;

	// IPartyService partyService;

	public boolean supports(Class clazz) {
		return clazz.equals(ControllerFormBean.class);
	}

	public void validate(Object obj, Errors errors) {
		ControllerFormBean form = (ControllerFormBean) obj;
		if (validateEmail(form.getEmailAddr(), errors)) {
			validateAccount(form.getEmailAddr(), form.getPassword(), errors);
		}
	}

	private boolean validateEmail(String email, Errors errors) {
		// ValidationUtils.rejectIfEmpty(errors, "email_addr",
		// "required.email_addr", "E-mail is required");
		Perl5Util perl5Util = new Perl5Util();
		if (email != null && !email.trim().equals("") && !perl5Util.match(EMAIL_REGEXP, email)) {
			logger.info("validateEmail email error,failed.");
			// errors.reject("party.partyId", "Invalid E-mail");
			errors.rejectValue("emailAddr", "Invalid E-mail", null, "电邮格式不正确");
			logger.info("Invalid E-mail,Failed.");
			return false;
		}
		return true;
	}

	private void validateAccount(String emailAddr, String password, Errors errors) {
		ValidationUtils.rejectIfEmpty(errors, "password", "required.password", "password is required");

		User user = userDao.findUserByUserId(emailAddr);
		if (user != null) {
			if (user.getPassword() != null && !user.getPassword().equals(password)) {
				logger.info("password error,failed.");
				errors.rejectValue("password", "Password Error", null, "电邮或密码不对");
			}
		} else {
			errors.rejectValue("password", "E-mail not exists", null, "电邮或密码不对");
			logger.info("Account does not exists");
		}
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

}